package com.ashley.phonemsn

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.IBinder
import android.telecom.TelecomManager
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.util.Log
import androidx.core.app.NotificationCompat

/**
 * 拨号拦截服务
 * 用于完全拦截系统的拨打电话和接听电话功能
 */
class CallInterceptService : Service() {
    private val TAG = "CallInterceptService"
    private val CHANNEL_ID = "call_intercept_channel"
    private val NOTIFICATION_ID = 1002

    private var telephonyManager: TelephonyManager? = null
    private var telecomManager: TelecomManager? = null
    private var phoneStateListener: PhoneStateListener? = null
    private var outgoingCallReceiver: BroadcastReceiver? = null

    // 拨号拦截状态
    private var isInterceptingOutgoing = false
    private var isInterceptingIncoming = false

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "拨号拦截服务已创建")
        
        // 初始化服务
        initServices()
        
        // 创建前台服务通知
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, createNotification())
        
        // 开始拦截
        startCallInterception()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "拨号拦截服务已启动")
        
        // 处理拦截指令
        intent?.let {
            when (it.action) {
                ACTION_START_INTERCEPT -> {
                    startCallInterception()
                }
                ACTION_STOP_INTERCEPT -> {
                    stopCallInterception()
                }
                ACTION_INTERCEPT_OUTGOING -> {
                    val phoneNumber = it.getStringExtra(EXTRA_PHONE_NUMBER)
                    interceptOutgoingCall(phoneNumber)
                }
                ACTION_INTERCEPT_INCOMING -> {
                    val phoneNumber = it.getStringExtra(EXTRA_PHONE_NUMBER)
                    interceptIncomingCall(phoneNumber)
                }
            }
        }
        
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null

    /**
     * 初始化服务
     */
    private fun initServices() {
        try {
            telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager
            telecomManager = getSystemService(Context.TELECOM_SERVICE) as? TelecomManager
            Log.d(TAG, "服务初始化成功")
        } catch (e: Exception) {
            Log.e(TAG, "服务初始化失败", e)
        }
    }

    /**
     * 开始电话拦截
     */
    private fun startCallInterception() {
        try {
            // 设置电话状态监听
            setupPhoneStateListener()
            
            // 设置拨出电话拦截
            setupOutgoingCallIntercept()
            
            isInterceptingOutgoing = true
            isInterceptingIncoming = true
            
            Log.d(TAG, "电话拦截已启动")
        } catch (e: SecurityException) {
            Log.e(TAG, "电话拦截权限不足", e)
        } catch (e: Exception) {
            Log.e(TAG, "启动电话拦截失败", e)
        }
    }

    /**
     * 停止电话拦截
     */
    private fun stopCallInterception() {
        try {
            // 移除电话状态监听
            removePhoneStateListener()
            
            // 移除拨出电话拦截
            removeOutgoingCallIntercept()
            
            isInterceptingOutgoing = false
            isInterceptingIncoming = false
            
            Log.d(TAG, "电话拦截已停止")
        } catch (e: Exception) {
            Log.e(TAG, "停止电话拦截失败", e)
        }
    }

    /**
     * 设置电话状态监听
     */
    private fun setupPhoneStateListener() {
        try {
            phoneStateListener = object : PhoneStateListener() {
                override fun onCallStateChanged(state: Int, incomingNumber: String?) {
                    if (!isInterceptingIncoming) return
                    
                    when (state) {
                        TelephonyManager.CALL_STATE_RINGING -> {
                            // 来电拦截
                            Log.d(TAG, "拦截到来电: $incomingNumber")
                            handleIncomingCallIntercept(incomingNumber)
                        }
                        TelephonyManager.CALL_STATE_OFFHOOK -> {
                            // 通话开始
                            Log.d(TAG, "通话开始")
                        }
                        TelephonyManager.CALL_STATE_IDLE -> {
                            // 通话结束
                            Log.d(TAG, "通话结束")
                        }
                    }
                }
            }

            telephonyManager?.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE)
            Log.d(TAG, "电话状态监听已设置")
        } catch (e: SecurityException) {
            Log.e(TAG, "设置电话状态监听权限不足", e)
        } catch (e: Exception) {
            Log.e(TAG, "设置电话状态监听失败", e)
        }
    }

    /**
     * 移除电话状态监听
     */
    private fun removePhoneStateListener() {
        try {
            if (phoneStateListener != null && telephonyManager != null) {
                telephonyManager?.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE)
                phoneStateListener = null
                Log.d(TAG, "电话状态监听已移除")
            }
        } catch (e: Exception) {
            Log.e(TAG, "移除电话状态监听失败", e)
        }
    }
    
    /**
     * 移除拨出电话拦截
     */
    private fun removeOutgoingCallIntercept() {
        try {
            // 在Android 10及以上版本，无需移除广播接收器
            outgoingCallReceiver = null
            Log.d(TAG, "拨出电话拦截已移除")
        } catch (e: Exception) {
            Log.e(TAG, "移除拨出电话拦截失败", e)
        }
    }

    /**
     * 设置拨出电话拦截
     */
    private fun setupOutgoingCallIntercept() {
        try {
            // 在Android 10及以上版本，PROCESS_OUTGOING_CALLS权限已废弃
            // 使用替代方案：监听拨号事件并重定向到应用内拨号
            
            // 注册拨号意图拦截
            outgoingCallReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context, intent: Intent) {
                    if (intent.action == Intent.ACTION_NEW_OUTGOING_CALL) {
                        val phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER)
                        if (phoneNumber != null && isInterceptingOutgoing) {
                            Log.d(TAG, "拦截到拨出电话: $phoneNumber")
                            
                            // 取消系统拨号
                            setResultData(null)
                            
                            // 重定向到应用内拨号
                            redirectToAppDialer(context, phoneNumber)
                        }
                    }
                }
            }
            
            // 注册广播接收器（在Android 10+中可能无法正常工作，但作为备选方案）
            val filter = IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL)
            registerReceiver(outgoingCallReceiver, filter)
            
            Log.d(TAG, "拨出电话拦截已设置（使用替代方案）")
        } catch (e: SecurityException) {
            Log.e(TAG, "设置拨出电话拦截权限不足", e)
        } catch (e: Exception) {
            Log.e(TAG, "设置拨出电话拦截失败", e)
        }
    }
    
    /**
     * 重定向到应用内拨号器
     */
    private fun redirectToAppDialer(context: Context, phoneNumber: String) {
        try {
            // 发送广播通知UI层有拨号请求
            sendInterceptBroadcast(ACTION_OUTGOING_INTERCEPTED, phoneNumber)
            
            // 启动应用内拨号界面
            val appDialerIntent = Intent(context, MainActivity::class.java).apply {
                action = "com.ashley.phonemsn.ACTION_APP_DIALER"
                putExtra(EXTRA_PHONE_NUMBER, phoneNumber)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            }
            context.startActivity(appDialerIntent)
            
            Log.d(TAG, "已重定向拨号请求到应用内拨号器: $phoneNumber")
        } catch (e: Exception) {
            Log.e(TAG, "重定向到应用内拨号器失败", e)
        }
    }

    /**
     * 拦截拨出电话
     */
    private fun interceptOutgoingCall(phoneNumber: String?) {
        try {
            Log.d(TAG, "拦截拨出电话: $phoneNumber")
            
            // 在Android 10及以上版本，使用应用内拨号替代系统拨号
            // 通知UI层使用应用内拨号功能
            sendInterceptBroadcast(ACTION_OUTGOING_INTERCEPTED, phoneNumber)
            
        } catch (e: Exception) {
            Log.e(TAG, "拦截拨出电话失败", e)
        }
    }

    /**
     * 处理来电拦截
     */
    private fun handleIncomingCallIntercept(phoneNumber: String?) {
        try {
            Log.d(TAG, "处理来电拦截: $phoneNumber")
            
            // 发送广播通知UI层有来电
            sendInterceptBroadcast(ACTION_INCOMING_INTERCEPTED, phoneNumber)
            
        } catch (e: Exception) {
            Log.e(TAG, "处理来电拦截失败", e)
        }
    }

    /**
     * 拦截来电
     */
    private fun interceptIncomingCall(phoneNumber: String?) {
        try {
            Log.d(TAG, "拦截来电: $phoneNumber")
            
            // 这里实现来电的拦截逻辑
            // 可以阻止系统来电界面，使用应用内接听界面
            
        } catch (e: Exception) {
            Log.e(TAG, "拦截来电失败", e)
        }
    }

    /**
     * 发送拦截广播
     */
    private fun sendInterceptBroadcast(action: String, phoneNumber: String?) {
        try {
            val intent = Intent(action).apply {
                putExtra(EXTRA_PHONE_NUMBER, phoneNumber)
                putExtra(EXTRA_TIMESTAMP, System.currentTimeMillis())
            }
            sendBroadcast(intent)
            Log.d(TAG, "发送拦截广播: $action")
        } catch (e: Exception) {
            Log.e(TAG, "发送拦截广播失败", e)
        }
    }

    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "拨号拦截服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "拨号拦截服务正在运行，用于拦截系统的拨打电话和接听电话功能"
            }
            
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    /**
     * 创建前台服务通知
     */
    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("拨号拦截服务")
            .setContentText("正在拦截系统电话功能")
            .setSmallIcon(android.R.drawable.ic_menu_call)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "拨号拦截服务已销毁")
        
        // 停止拦截
        stopCallInterception()
        
        // 清理资源
        telephonyManager = null
        telecomManager = null
        phoneStateListener = null
        
        // 取消注册广播接收器
        try {
            outgoingCallReceiver?.let {
                unregisterReceiver(it)
            }
        } catch (e: Exception) {
            Log.w(TAG, "取消注册广播接收器时出错", e)
        }
        outgoingCallReceiver = null
    }

    companion object {
        // 动作常量
        const val ACTION_START_INTERCEPT = "com.ashley.phonemsn.ACTION_START_INTERCEPT"
        const val ACTION_STOP_INTERCEPT = "com.ashley.phonemsn.ACTION_STOP_INTERCEPT"
        const val ACTION_INTERCEPT_OUTGOING = "com.ashley.phonemsn.ACTION_INTERCEPT_OUTGOING"
        const val ACTION_INTERCEPT_INCOMING = "com.ashley.phonemsn.ACTION_INTERCEPT_INCOMING"
        
        // 广播动作
        const val ACTION_OUTGOING_INTERCEPTED = "com.ashley.phonemsn.ACTION_OUTGOING_INTERCEPTED"
        const val ACTION_INCOMING_INTERCEPTED = "com.ashley.phonemsn.ACTION_INCOMING_INTERCEPTED"
        
        // 额外参数
        const val EXTRA_PHONE_NUMBER = "phone_number"
        const val EXTRA_TIMESTAMP = "timestamp"
        
        /**
         * 启动拦截服务
         */
        fun startService(context: Context) {
            val intent = Intent(context, CallInterceptService::class.java).apply {
                action = ACTION_START_INTERCEPT
            }
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }
        
        /**
         * 停止拦截服务
         */
        fun stopService(context: Context) {
            val intent = Intent(context, CallInterceptService::class.java).apply {
                action = ACTION_STOP_INTERCEPT
            }
            context.stopService(intent)
        }
        
        /**
         * 拦截拨出电话
         */
        fun interceptOutgoingCall(context: Context, phoneNumber: String?) {
            val intent = Intent(context, CallInterceptService::class.java).apply {
                action = ACTION_INTERCEPT_OUTGOING
                putExtra(EXTRA_PHONE_NUMBER, phoneNumber)
            }
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }
        
        /**
         * 拦截来电
         */
        fun interceptIncomingCall(context: Context, phoneNumber: String?) {
            val intent = Intent(context, CallInterceptService::class.java).apply {
                action = ACTION_INTERCEPT_INCOMING
                putExtra(EXTRA_PHONE_NUMBER, phoneNumber)
            }
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }
    }
}